package com.ruoyi.web.controller.wnjk.shop;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.wnjk.contents.Contents;
import com.ruoyi.system.wnjk.domain.dto.ShopAfterSalesRequestsDTO;
import com.ruoyi.system.wnjk.domain.po.*;
import com.ruoyi.system.wnjk.service.*;
import com.ruoyi.system.wnjk.producer.RefundProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 售后详情Controller
 *
 * @author ruoyi
 * @date 2025-03-07
 */
@RestController
@RequestMapping("/shop/after_sales_requests")
public class ShopAfterSalesRequestsController extends BaseController
{
    @Autowired
    private IShopAfterSalesRequestsService shopAfterSalesRequestsService;

    @Autowired
    private IShopOrderService shopOrderService;

    @Autowired
    private IShopItemService shopItemService;

    @Autowired
    private IShopOrderDetailService shopOrderDetailService;

    @Autowired
    private IShopLogisticsDetailsService logisticsDetailsService;

    @Autowired
    private RefundProducer refundProducer;

    @Autowired
    private IShopPayOrderService shopPayOrderService;


    /**
     * 查询售后详情列表
     */
    @PreAuthorize("@ss.hasPermi('shop:after_sales_requests:list')")
    @GetMapping("/list")
    public TableDataInfo list(ShopAfterSalesRequests shopAfterSalesRequests)
    {
        startPage();
        List<ShopAfterSalesRequests> list = shopAfterSalesRequestsService.selectShopAfterSalesRequestsList(shopAfterSalesRequests);
        return getDataTable(list);
    }

    /**
     * 导出售后详情列表
     */
    @PreAuthorize("@ss.hasPermi('shop:after_sales_requests:export')")
    @Log(title = "售后详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ShopAfterSalesRequests shopAfterSalesRequests)
    {
        List<ShopAfterSalesRequests> list = shopAfterSalesRequestsService.selectShopAfterSalesRequestsList(shopAfterSalesRequests);
        ExcelUtil<ShopAfterSalesRequests> util = new ExcelUtil<ShopAfterSalesRequests>(ShopAfterSalesRequests.class);
        util.exportExcel(response, list, "售后详情数据");
    }

    /**
     * 获取售后详情详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:after_sales_requests:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(shopAfterSalesRequestsService.selectShopAfterSalesRequestsById(id));
    }

    /**
     * 新增售后详情
     */
    @PreAuthorize("@ss.hasPermi('shop:after_sales_requests:add')")
    @Log(title = "售后详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ShopAfterSalesRequests shopAfterSalesRequests)
    {
        return toAjax(shopAfterSalesRequestsService.insertShopAfterSalesRequests(shopAfterSalesRequests));
    }

    /**
     * 修改售后详情
     */
    @PreAuthorize("@ss.hasPermi('shop:after_sales_requests:edit')")
    @Log(title = "售后详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ShopAfterSalesRequests shopAfterSalesRequests)
    {
        return toAjax(shopAfterSalesRequestsService.updateShopAfterSalesRequests(shopAfterSalesRequests));
    }

    /**
     * 删除售后详情
     */
    @PreAuthorize("@ss.hasPermi('shop:after_sales_requests:remove')")
    @Log(title = "售后详情", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(shopAfterSalesRequestsService.deleteShopAfterSalesRequestsByIds(ids));
    }

    @PostMapping("/refuse/{id}")
    public AjaxResult refuse(@PathVariable("id") Long id){
        boolean flag = shopAfterSalesRequestsService.refuseAfterSalesRequest(id);
        return flag? success():error();
    }

    /**
     * 同意售后 （退款/换货）
     */
    @Transactional
    @PutMapping("/agree")
    public AjaxResult agree(@RequestBody ShopAfterSalesRequestsDTO shopAfterSalesRequestsDTO){
        System.out.println(shopAfterSalesRequestsDTO);
//        if (shopAfterSalesRequestsDTO!=null){
//           return error();
//        }
        //1.检查订单是否存在
        ShopOrder shopOrder = shopOrderService.selectShopOrderById(shopAfterSalesRequestsDTO.getOrderId());
        if (shopOrder == null){
            return error("订单不存在");
        }
        //检查订单状态
        if (shopOrder.getStatus() == Contents.Shop.ORDER_STATUS_SHIPPED_CONFIRMED){
            //拒绝，超时订单不能申请售后,同时修改售后订单状态
            ShopAfterSalesRequests shopAfterSalesRequests = shopAfterSalesRequestsService.selectShopAfterSalesRequestsById(shopAfterSalesRequestsDTO.getId());
            shopAfterSalesRequests.setRequestStatus(Contents.Shop.REQUESTS_STATUS_REJECTED);
            shopAfterSalesRequestsService.updateShopAfterSalesRequests(shopAfterSalesRequests);
            return error("当前订单已经不允许售后");
        }
        if (shopAfterSalesRequestsDTO.getRequestType().equals(Contents.Shop.AFTER_SALES_REQUESTS_STATUS_REFUND)){
            //退款
            // 直接使用MQ  向mq发送消息
            notifyRefundQueue(shopAfterSalesRequestsDTO,shopOrder);

        }else if (shopAfterSalesRequestsDTO.getRequestType().equals(Contents.Shop.AFTER_SALES_REQUESTS_STATUS_EXCHANGE)){
            //换货
            //2.通过订单表和订单详情表检查商品是否还有库存
            ShopOrderDetail shopOrderDetailQueryCondition = new ShopOrderDetail();
            shopOrderDetailQueryCondition.setOrderId(shopOrder.getId());
            //2.1.找到订单中的每一条信息
            List<ShopOrderDetail> shopOrderDetails = shopOrderDetailService.selectShopOrderDetailList(shopOrderDetailQueryCondition);
            //是否还有库存
            boolean hasStock = hasItemStock(shopOrderDetails);
            //3.换货/退款处理
            if (hasStock){
                //还有库存，执行换货
                deductInventory(shopOrderDetails);
                //3.换货相关
                //3.1.添加新物流信息
                 logisticsDetailsService.createLogistics(shopOrder);
            }else {
                //没有库存，执行退款
                //退款通过普通队列执行
                //在mq消费消息后执行 修改售后结果
                notifyRefundQueue(shopAfterSalesRequestsDTO,shopOrder);
            }
        }
        return success();
    }

    private void notifyRefundQueue(ShopAfterSalesRequestsDTO shopAfterSalesRequestsDTO, ShopOrder shopOrder) {
        ShopPayOrder shopPayOrder = shopPayOrderService.selectShopPayOrderById(shopOrder.getId());
        refundProducer.sendRefundRequest(
                shopAfterSalesRequestsDTO.getOrderId().toString(),
                Contents.Pay.TYPE_GW_SHOP,
                shopPayOrder.getPayOrderNo().toString(),
                shopAfterSalesRequestsDTO.getReason(),
                shopAfterSalesRequestsDTO.getAmount().toString()
        );
    }

    /**
     * 扣减库存
     * @param shopOrderDetails
     */
    private void deductInventory(List<ShopOrderDetail> shopOrderDetails) {
        for (ShopOrderDetail orderDetailItem : shopOrderDetails){
            //获取每个商品信息
            ShopItem shopItem = shopItemService.selectShopItemById(orderDetailItem.getItemId());
            //扣减库存
            shopItem.setStock(shopItem.getStock()-1);
            shopItemService.updateShopItem(shopItem);
        }
    }

    /**
     * 判断是否还有库存
     * @param shopOrderDetails
     * @return
     */
    private boolean hasItemStock(List<ShopOrderDetail> shopOrderDetails) {
        boolean hasStock = true;
        for (ShopOrderDetail orderDetailItem : shopOrderDetails) {
            //获取每个商品信息
            ShopItem shopItem = shopItemService.selectShopItemById(orderDetailItem.getItemId());
            //2.2.判断是否还有库存
            if (shopItem.getStock() == 0){
                //没有库存
                hasStock = false;
                break;
            }
        }
        return hasStock;
    }
}
